package com.rytong.tools.ui;

import java.util.Vector;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.TextView;

//保存html中的文字 如 <p>

public class LPHtmlText extends Component {
    private static int MAX_PARAGRAPH_WIDTH = SCREENWIDTH - 10;
    private static int ADDW = 3;
    /** A list of line breaks. */
    private Vector strings_;
    private int totalLink_;

    static final float Y_MARGIN = 1.3f;
    private int currentSelect_ = -1;

    int left_; // Relative left position to the left of the FULL canvas.
    int top_; // Relative left position to the top of the FULL canvas.
    protected int clickedColor_;

    protected CssStyle cssStyle_;
    public CssStyle pseudoStyle_;
    public String linkAddr_;
    boolean isHyperLink_;
    protected boolean isClicked_ = false;
    boolean focus_;

    private boolean isTrimHeadBlank_;
    private boolean isBreakWord_;

    String isEncrypt_;
    
    // occupies more than one line, and NOT start at the
    // head of the line.

    public class MyLPHtmlText extends TextView implements CompositedComponent {
        public MyLPHtmlText(Context context, String text) {
            super(context);
            // TODO Auto-generated constructor stub
            property_.put("text", text);
            setText(text);
            this.setFocusableInTouchMode(true);
            totalLink_ = 0;
        }

        @Override
        public Component composited() {
            // TODO Auto-generated method stub
            return LPHtmlText.this;
        }

        // 焦点改变时调用该方法
        // protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        // if (gainFocus) {
        // BaseView bv = (BaseView) this.getContext();
        // bv.stopTicker();
        // }
        // super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
        // }

        public boolean onKeyUp(int keyCode, KeyEvent event) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                isClicked_ = true;
                dealWithLink(linkAddr_, (Activity) this.getContext());
                break;
            default:
                return super.onKeyDown(keyCode, event);
            }
            return true;
        }

        public boolean onKeyDown(int keyCode, KeyEvent event) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:

                break;
            default:
                return super.onKeyDown(keyCode, event);
            }
            return true;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (getPropertyByName("loop").toString().equalsIgnoreCase("true"))
                drawMoveStr(this, canvas, getWidth(), getPaint(), (String) getText(), 0,
                        ((int) (getHeight() + getPaint().getTextSize())) >> 1);
            else {
                // super.onDraw(canvas);
                // 下面手动绘制label上的文字，不再调用系统的方法了
                paint_ = getPaint();
                paint_.setAntiAlias(true); // 抗锯齿。
                // int text_height = (int) paint_.getTextSize();// 文字高度
                int text_height = ((int) (paint_.getTextSize() * 3)) >> 2;
                if (null == stringArr_) {
                    return;
                }
                int length = stringArr_.length;
                if (length == 1) {
                    blankY_ = 0;
                    text_height = ((text_height + getHeight()) >> 1);
                }
                // 取后台给的宽度值，如果给了宽度值则textAlign_相对于label本身有效果
                String w = "";
                if (null != cssStyle_)
                    w = cssStyle_.getProperty(CssStyle.WIDTH);
                // 初始高度为留白高+字高
                float coordinate_y = Utils.getScaledValueY(blankY_) + text_height;
                for (int i = 0; i < length; i++) {
                    if (i > 0)
                        coordinate_y += text_height + Utils.getScaledValueY(SPACE_Y_);
                        canvas.drawText(stringArr_[i], 0, coordinate_y, paint_);
                }
            }
        }
        
        public boolean onTouchEvent(MotionEvent event) {
            int touchEvent = event.getAction();
            boolean isAction = false;
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                yDown_ = event.getY();
                isAction = true;
                this.requestFocus();
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            	}
                moveY(yDown_, event.getY());
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                // 预防控件出现连击效果
                long currentTime = System.currentTimeMillis();
                long timedifference = currentTime - LASTCLICKTIME;
                if (timedifference < 0) {
                    LASTCLICKTIME = currentTime;
                } else if (timedifference < jetLag_) {
                    LASTCLICKTIME = currentTime;
                    return false;
                } else {
                    LASTCLICKTIME = currentTime;
                }
                isClicked_ = true;

                if ("" != getPropertyByName("onclick")) {
                    onClick((String) composited().property_.get("onclick"));
                } else {
                    isAction = dealWithLink(linkAddr_, (Activity) realView_.getContext());
                }
                break;
            default:
                return super.onTouchEvent(event);
            }
            return isAction;
        }
    }

    void setToLink(String linkTarget) {
        linkAddr_ = linkTarget;
    }

    public int getLPHeight() {
        // TODO Auto-generated method stub
        return height_;
    }

    public int getLPWidth() {
        // TODO Auto-generated method stub
        return width_;
    }

    public void mouldH() {
        try {
            super.mouldH();
            linkAddr_ = (String) getPropertyByName("href");
            // 设置超链接文本下划线效果
            getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            reSetTextViewLayoutParams();
            LayoutParams lp = (LayoutParams) getLayoutParams();
            //增加2像素线的高度，以保证下划线能显示出来
            lp.height = lp.height + 2;
            setLayoutParams(lp);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    public void setBackgroundColor(int backgroundColor) {
        // TODO Auto-generated method stub
        realView_.setBackgroundColor(backgroundColor);
    }

    public void setFocusable(boolean b) {
        // TODO Auto-generated method stub
        realView_.setFocusable(b);
    }

    public int getHeight() {
        // TODO Auto-generated method stub
        return realView_.getHeight();
    }

    public int getWidth() {
        // TODO Auto-generated method stub
        return realView_.getWidth();
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPHtmlText(activity, value);
    }

    @Override
    public void releaseResource(Component component) {
    	super.releaseResource(component);
    	if(strings_ != null){
    		strings_.clear();
    		strings_ = null;
    	}
    }
}
